package userShareModuleApi

import (
	"KumquatDrivesServices/common/res"
	"KumquatDrivesServices/enums"
	"KumquatDrivesServices/global"
	"KumquatDrivesServices/model"
	"errors"
	"github.com/gin-gonic/gin"
	"github.com/sirupsen/logrus"
	"gorm.io/gorm"
)

type getShareFileListReq struct {
	ShareId string                `uri:"shareId" binding:"required"`
	FilePid model.SnowflakeIdType `uri:"filePid"`
}

func (UserShareModuleApi) GetShareFileList(c *gin.Context) {
	var req getShareFileListReq
	if err := c.ShouldBindUri(&req); err != nil {
		logrus.Errorf("GetShareFileList error :%v", err)
		res.FailWithCode(res.PARAM_ERR, c)
		return
	}
	shareAuthInfo, err := checkShareAuthState(req.ShareId, c)
	if err != nil {
		res.FailWithCode(res.SHARE_EXPIRED_REVERIFY, c)
		return
	}
	var fileList []model.FileModel
	query := global.DB.Where("id=? and user_id=? and del_flag=?", shareAuthInfo.ShareFileId, shareAuthInfo.ShareUserId, enums.Normal)
	if req.FilePid != 0 && req.FilePid != 1 {
		bol, e := isFileWithinSharedFolder(shareAuthInfo.ShareFileId, req.FilePid, shareAuthInfo.ShareUserId)
		if e != nil {
			logrus.Errorf("isFileWithinSharedFolder error :%v", e)
			res.FailWithCode(res.SYS_ERR, c)
			return
		}
		if !bol {
			res.FailWithCode(res.PARAM_ERR, c)
			return
		}
		query = global.DB.Where("file_pid=? and user_id=? and del_flag=?", req.FilePid, shareAuthInfo.ShareUserId, enums.Normal)
	}
	if er := query.Find(&fileList).Error; er != nil {
		if errors.Is(er, gorm.ErrRecordNotFound) {
			res.FailWithCode(res.PARAM_ERR, c)
			return
		}
		logrus.Errorf("GetShareFileList error :%v", er)
		res.FailWithCode(res.SYS_ERR, c)
		return
	}
	res.OkWithData(fileList, c)
}
